package edu.xmut.yuepai.common.cos;

import cn.hutool.core.date.DateUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.DispatcherServlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

@ConditionalOnClass(DispatcherServlet.class)
@Component
public class COSUtils implements DisposableBean, InitializingBean {

    @Value("${yuepai.cos.secret-id}")
    private String secretId;
    @Value("${yuepai.cos.secret-key}")
    private String secretKey;
    private COSClient cosClient;

    @Override
    public void afterPropertiesSet() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-guangzhou");
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 设置 socket 读取超时，默认 30s
        clientConfig.setSocketTimeout(10 * 1000);
        // 设置建立连接超时，默认 30s
        clientConfig.setConnectionTimeout(10 * 1000);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }


    public COSUploadPictureResult uploadPicture(MultipartFile multipartFile, String key) {
        // 图片的类型
        String contentType = multipartFile.getContentType();
        // 图片的大小
        long size = multipartFile.getSize();
        // 图片流
        InputStream inputStream;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String[] keys = key.split("\\.");
        // 指定文件将要存放的存储桶
        String bucketName = "yuepai-1308017514";
        // 构造目录格式
        String directory = DateUtil.today().replace("-", "/") + "/";
        // 指定文件上传到 COS 上的路径，即对象键。
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(size);
        objectMetadata.setContentType(contentType);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, directory + key, inputStream, objectMetadata);
        // 创建图片处理对象
        PicOperations picOperations = new PicOperations();
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> ruleList = new LinkedList<>();
        // 添加图片处理规则
        PicOperations.Rule rule1 = new PicOperations.Rule();
        rule1.setBucket(bucketName);
        rule1.setFileId(keys[0] + "_preview." + keys[1]);
        rule1.setRule("imageMogr2/thumbnail/!20p");
        ruleList.add(rule1);
        // 设置图片规则
        picOperations.setRules(ruleList);
        // 设置图片操作
        putObjectRequest.setPicOperations(picOperations);
        // 设置存储类型（如有需要，不需要请忽略此行代码）, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);
        // 执行上传动作
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        String originalLocation = putObjectResult.getCiUploadResult().getOriginalInfo().getLocation();
        Integer height = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo().getHeight();
        Integer width = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo().getWidth();
        String processLocation = putObjectResult.getCiUploadResult().getProcessResults().getObjectList().get(0).getLocation();
        // 返回结果
        return COSUploadPictureResult.builder()
                .defaultUrl("https://" + originalLocation)
                .previewUrl("https://" + processLocation)
                .width(width)
                .height(height)
                .build();
    }


    @Override
    public void destroy() {
        cosClient.shutdown();
    }


}
